package com.mingweicai.intergration.test;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

class ZeroEvenOdd {
  private int n;
  Semaphore semaphoreA = new Semaphore(1);
  Semaphore semaphoreB = new Semaphore(0);
  Semaphore semaphoreC = new Semaphore(0);

  public ZeroEvenOdd(int n) {
    this.n = n;
  }

  // printNumber.accept(x) outputs "x", where x is an integer.
  public void zero(IntConsumer printNumber) throws InterruptedException {
    for(int i=1;i<=2*n;i++){
      semaphoreA.acquire();
      printNumber.accept(i);
      if((i & 2) == 0){
        semaphoreC.release();
      }else{
        semaphoreB.release();
      }
    }
  }

  public void even(IntConsumer printNumber) throws InterruptedException {
    for(int i=1;i<=2*n;i+=2){
      semaphoreB.acquire();
      printNumber.accept(i);
      semaphoreA.release();
    }
  }

  public void odd(IntConsumer printNumber) throws InterruptedException {
    for(int i=2;i<=2*n;i+=2){
      semaphoreC.acquire();
      printNumber.accept(i);
      semaphoreA.release();
    }
  }
}